﻿//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;

//namespace framework4._6._2
//{
//    internal class Program
//    {
//        static void Main(string[] args)
//        {
//        }
//    }
//}


using System;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;

namespace framework4._6._2
{
    class HMAC
    {
        public static void Main()
        {
            string json = File.ReadAllText("D:\\code\\dotnet\\training-dotnet-master\\assets\\reqBody.json");
            //dynamic data = JsonConvert.DeserializeObject(json);
            // Formatting.None去掉空格
            string body = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.None);
            string secret = "ts@1698204817|route@/studio/api_special/insuite/stk_simple_pro_in/create|sec@SN7to7cTxvW7Om5J4H53reFybehtonHm|method@post";
            byte[] k = sha512Hash(secret);
            //string body = "{\"1\":222,\"2\":999,\"3\":[\"22\",1]}";
            byte[] sign = HmacSHA256(body, k);
            //string signStr = Convert.ToHexString(sign).ToLower();
            string signStr = BitConverter.ToString(sign, 0).Replace("-", string.Empty).ToLower();//byte[]转十六进制字符串
            Console.WriteLine(signStr);
            return;
        }

        public static byte[] HmacSHA256(string body, byte[] signKey)
        {
            byte[] signRet;
            using (HMACSHA256 mac = new HMACSHA256(signKey))
            {
                signRet = mac.ComputeHash(Encoding.UTF8.GetBytes(body));
                // signRet = Convert.ToBase64String(hash);
                // signRet = ToHexString(hash); 
            }
            return signRet;
        }

        public static byte[] sha512Hash(string source)
        {
            string result = string.Empty;
            byte[] buffer = Encoding.UTF8.GetBytes(source);//UTF-8 编码

            //64字节,512位
            SHA512 sha512 = SHA512.Create();
            byte[] h5 = sha512.ComputeHash(buffer);

            Console.WriteLine(BitConverter.ToString(h5, 0).Replace("-", string.Empty).ToLower());

            return h5;
        }
    }
}